package com.tiyende.kash.loop.weight.city

/**
 * Created by YoKey on 16/10/7.
 */
internal class CityDataComparator<T : IndexableEntity?> : Comparator<EntityWrapper<T>> {
    override fun compare(lhs: EntityWrapper<T>, rhs: EntityWrapper<T>): Int {
        var lhsIndexName = lhs.getIndexByField()
        var rhsIndexName = rhs.getIndexByField()
        if (lhsIndexName == null) {
            lhsIndexName = ""
        }
        if (rhsIndexName == null) {
            rhsIndexName = ""
        }
        return compareIndexName(lhsIndexName.trim { it <= ' ' }, rhsIndexName.trim { it <= ' ' })
    }

    private fun compareIndexName(lhs: String, rhs: String): Int {
        var index = 0
        var lhsWord = getWord(lhs, index)
        var rhsWord = getWord(rhs, index)
        while (lhsWord == rhsWord && lhsWord != "") {
            index++
            lhsWord = getWord(lhs, index)
            rhsWord = getWord(rhs, index)
        }
        return lhsWord.compareTo(rhsWord)
    }

    private fun getWord(indexName: String, index: Int): String {
        if (indexName.length < index + 1) return ""
        val firstWord: String = if (CityDataUtil.matchingPolyphone(indexName)) {
            CityDataUtil.getCityNameLowercase(
                CityDataUtil.getPolyphoneRealHanzi(indexName).substring(index, index + 1)
            )
        } else {
            CityDataUtil.getCityNameLowercase(indexName.substring(index, index + 1))
        }
        return firstWord
    }
}
